package _01_动态数组;

import java.util.*;

public class _剑指_OfferII060_出现频率最高的k个数字 {

    public static void main(String[] args) {

        _剑指_OfferII060_出现频率最高的k个数字 v = new _剑指_OfferII060_出现频率最高的k个数字();

        int[] ins = new int[]{1, 1, 1, 2, 2, 3};
        int k = 2;
        int[] ints = v.topKFrequent(ins, k);

        for (int anInt : ints) {
            System.out.println(anInt);
        }

    }

    public int[] topKFrequent(int[] nums, int k) {
        Map<Integer, Integer> results = new HashMap<>();
        for (int num : nums) {
            results.put(num, results.getOrDefault(num, 0) + 1);
        }
        ArrayList<Map.Entry<Integer, Integer>> list = new ArrayList<>(results.entrySet());
        list.sort((a1, a2) -> a2.getValue() - a1.getValue());
        int[] res = new int[k];
        for (int i = 0; i < k; i++) {
            res[i] = list.get(i).getKey();
        }
        return res;
    }

}
